package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.configure.DelayedMqOrderConfig;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.SkuLockVo;
import com.spzx.product.domain.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper,OrderInfo> implements IOrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    RemoteCartService remoteCartService;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Autowired
    RabbitService rabbitService;


    @Override
    public TradeVo trade() {
        Long userId = SecurityContextHolder.getUserId();
        String TradeNo = generateTradeNo(userId);

        TradeVo tradeVo = new TradeVo();

        List<OrderItem> orderItemList = new ArrayList<>();
        R<List<CartInfo>> cartInfoListR =remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        List<CartInfo> cartInfoList = cartInfoListR.getData();

        orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuPrice(cartInfo.getSkuPrice());
//            orderItem.setOrderId();
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setThumbImg(cartInfo.getThumbImg());
            return orderItem;
        }).collect(Collectors.toList());

        tradeVo.setOrderItemList(orderItemList);
        BigDecimal sum = new BigDecimal("0");
        for(OrderItem orderItem : orderItemList){
            sum =sum.add(orderItem.getSkuPrice().multiply(new BigDecimal((orderItem.getSkuNum()))));
        }
        tradeVo.setTradeNo(TradeNo);
        tradeVo.setTotalAmount(sum);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        // 获取订单项目
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        String remark = orderForm.getRemark();
        String tradeNo = orderForm.getTradeNo();
        BigDecimal feightFee = orderForm.getFeightFee();

        // 检查交易码
        Long userId = SecurityContextHolder.getUserId();
        //取得缓存的交易码key
        String userTradeKey = "user:tradeNo:" + userId;
        //取得缓存的value
        String cacheTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        //判断交易码是否一致
        Assert.isTrue(cacheTradeNo.equals(tradeNo),"交易码无效");
        // 删除交易码
        redisTemplate.delete(userTradeKey);

        //检查价格

        // 获取商品价格
        List<Long> skuIds = orderItemList.stream().map(orderItem -> {
            Long skuId = orderItem.getSkuId();
            return skuId;
        }).collect(Collectors.toList());
        // 接口一
        List<SkuPrice> skuPrices = remoteProductService.getSkuPriceList(skuIds, SecurityConstants.INNER).getData();
        // 转化skuPrice为Map方便后续比较
        Map<Long, BigDecimal> priceMap = skuPrices.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        for (OrderItem orderItem : orderItemList) {
            Long skuId = orderItem.getSkuId();
            BigDecimal skuPrice = orderItem.getSkuPrice();

            Assert.isTrue(priceMap.get(skuId).compareTo(skuPrice)==0,"价格不一致，取消提交");
        }


        //锁定库存
        // 获取需要锁定的skuId和数量
        List<SkuLockVo> skuLockVos = orderItemList.stream().map(orderItem -> {
            Long skuId = orderItem.getSkuId();
            Integer skuNum = orderItem.getSkuNum();
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(skuId);
            skuLockVo.setSkuNum(skuNum);
            return skuLockVo;
        }).collect(Collectors.toList());
        //调用远程服务检查库存并锁定库存
        // 接口二 tradeNo:交易码，也是订单号
//        R<String> stringR = remoteProductService.checkAndLock(tradeNo, skuLockVos, INNER);
//        String errMsg = stringR.getData();
        String errMsg = remoteProductService.checkAndLock(tradeNo,skuLockVos,SecurityConstants.INNER).getData();
        Assert.isTrue(StringUtils.isEmpty(errMsg), errMsg);


        // 保存订单信息
        Long orderId = saveOrder(orderForm);


        //使用消息队列异步锁定库存
        rabbitService.sendDelayMessage(DelayedMqOrderConfig.EXCHANGE_ORDER_CANCEL_DELAY,
                DelayedMqOrderConfig.ROUTING_ORDER_CANCEL_DELAY,orderForm.getTradeNo(),20);
        // 接口三 删除购物车
        remoteCartService.removeCheckedCart(skuIds, SecurityConstants.INNER);
        return orderId;
    }

    @Override
    public void cancelOrder(String orderNo) {
        // 根据orderNo查询订单
        OrderInfo orderInfo = orderInfoMapper.selectOne(new QueryWrapper<OrderInfo>().eq("order_no", orderNo));
        Integer orderStatus = orderInfo.getOrderStatus();
        if(orderStatus==0){
            // 用户还未支付，关闭订单
            orderInfo.setOrderStatus(-1);
            orderInfoMapper.updateById(orderInfo);
            // 解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderNo);
        }

    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {

        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("order_no",orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(orderInfoQueryWrapper);
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id",orderInfo.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQueryWrapper);
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public void updateOrderSuccess(String orderNo) {
        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("order_no",orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(orderInfoQueryWrapper);
        orderInfo.setOrderStatus(2);
        baseMapper.updateById(orderInfo);
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }
}
